/*
 * Copyright 2007 Peter Zelenay.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *     
 */
package net.zelenay.jcrviewer.tree;

import java.util.Observable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;

import javax.jcr.Node;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import net.zelenay.jcrviewer.dao.ActiveNode;

/**
 * 
 * @author Peter Zelenay
 * 
 */
public class AsyncTree extends JTree {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final TreeExpansionListener expansionListener = new TreeExpansionListener() {

		public void treeCollapsed(final TreeExpansionEvent event) {
			final AsyncNode parent = (AsyncNode) event.getPath().getLastPathComponent();
			parent.removeAllChildren();
			DefaultTreeModel model = (DefaultTreeModel) ((JTree) event.getSource()).getModel();
			model.nodeStructureChanged(parent);
		}

		public void treeExpanded(final TreeExpansionEvent event) {
			final AsyncNode parent = (AsyncNode) event.getPath().getLastPathComponent();
			parent.setProcessing(true);

			FutureTask<AsyncNode[]> task = new FutureTask<AsyncNode[]>(new Callable<AsyncNode[]>() {
				public AsyncNode[] call() throws Exception {
					Thread.sleep(1000);
					return getNodeProvider().getChild(parent);
				}
			}) {
				@Override
				protected void done() {
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							AsyncNode[] nodes;
							try {
								nodes = get();
								parent.removeAllChildren();
								for (int i = 0; i < nodes.length; i++) {
									parent.insert(nodes[i], i);
								}
								DefaultTreeModel model = (DefaultTreeModel) ((JTree) event.getSource()).getModel();
								parent.setProcessing(false);
								model.nodeStructureChanged(parent);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ExecutionException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					});
				}
			};

			getExecutor().execute(task);

		}
	};

	private final TreeSelectionListener selectionListener = new TreeSelectionListener() {

		public void valueChanged(TreeSelectionEvent e) {
			AsyncNode treeNode = (AsyncNode) getSelectionPath().getLastPathComponent();
			Node o = (Node) treeNode.getUserObject();
			activeNode.setActiveNode(o);
		}
		
	};
	
	private NodeProvider nodeProvider;

	private Executor executor;
	
	private ActiveNode activeNode;

	public AsyncTree() {
		super();
		DefaultTreeModel model = (DefaultTreeModel) getModel();
		model.setAsksAllowsChildren(true);
		AsyncNode root = new AsyncNode("root", true);
		model.setRoot(root);
		addTreeExpansionListener(expansionListener);
		addTreeSelectionListener(selectionListener);
	}

	/**
	 * @return the nodeProvider
	 */
	public NodeProvider getNodeProvider() {
		return nodeProvider;
	}

	/**
	 * @param aNodeProvider
	 *            the nodeProvider to set
	 */
	public void setNodeProvider(NodeProvider aNodeProvider) {
		this.nodeProvider = aNodeProvider;
		
		expansionListener.treeExpanded(new TreeExpansionEvent(this, new TreePath(getModel().getRoot())));
		invalidate();
	}

	/**
	 * @return the executor
	 */
	public Executor getExecutor() {
		return executor;
	}

	/**
	 * @param aExecutor
	 *            the executor to set
	 */
	public void setExecutor(Executor aExecutor) {
		this.executor = aExecutor;
	}

	public ActiveNode getActiveNode() {
		return activeNode;
	}

	public void setActiveNode(ActiveNode activeNode) {
		this.activeNode = activeNode;
	}

}
